package com.firebird.app.reader.pdf.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.firebird.app.reader.pdf.activity.PDFSearchActivity
import com.tbruyelle.rxpermissions2.Permission
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.functions.Consumer

class FindPdfActivity : AppCompatActivity() {
    private var btnUpload: Button? = null
    private var ivBack: ImageView? = null
    private var tvTitle: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_find_pdf)
        initViews()
        requestPermission()
    }

    private fun initViews() {
        btnUpload = findViewById(R.id.tv_upload)
        ivBack = findViewById(R.id.iv_back)
        tvTitle = findViewById(R.id.tv_title)
        tvTitle.setText("PDFSearch")
        ivBack.setVisibility(View.GONE)
        btnUpload.setOnClickListener(View.OnClickListener { startActivity(Intent(this@FindPdfActivity, PDFSearchActivity::class.java)) })
    }

    @SuppressLint("InlinedApi")
    private fun requestPermission() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(object : Consumer<Permission?>() {
                    fun accept(permission: Permission) {
                        if (permission.granted) { // 用户已经同意该权限
                            Log.d(TAG, permission.name.toString() + " is granted.")
                        } else if (permission.shouldShowRequestPermissionRationale) { // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            Log.d(TAG, permission.name.toString() + " is denied. More info should be provided.")
                            Toast.makeText(this@FindPdfActivity, "您已拒绝了权限", Toast.LENGTH_SHORT).show()
                        } else { // 用户拒绝了该权限，并且选中『不再询问』
                            Log.d(TAG, permission.name.toString() + " is denied.")
                            Toast.makeText(this@FindPdfActivity, "您已拒绝了权限", Toast.LENGTH_SHORT).show()
                        }
                    }
                })
    }

    companion object {
        private val TAG: String = getSimpleName()
    }
}